package com.wwj.aicodemother.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wwj.aicodemother.exception.ErrorCode;
import com.wwj.aicodemother.exception.ThrowUtils;
import com.wwj.aicodemother.manager.CosManager;
import com.wwj.aicodemother.service.ScreenshotService;
import com.wwj.aicodemother.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@Slf4j
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private CosManager cosManager;
    /**
     * 生成并上传截图,可以得到访问地址
     * @param webUrl
     * @return
     */
    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        //参数校验
        ThrowUtils.throwIf(StrUtil.isBlank(webUrl), ErrorCode.NOT_FOUND_ERROR, "weburl不能为空");
        log.info("开始生成并上传截图,weburl:{}", webUrl);
        //本地截图
        String localScreenshotPath = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.NOT_FOUND_ERROR, "网页截图生成失败");
        //上传到cos
        try {
            String cosUrl = uploadScreenshot(localScreenshotPath);
            ThrowUtils.throwIf(StrUtil.isBlank(cosUrl), ErrorCode.NOT_FOUND_ERROR, "上传截图到对象存储失败");
            log.info("截图上传成功,cosUrl:{}", cosUrl);
            return cosUrl;
        } finally {
            //清理本地文件
            cleanupLocalScreenshot(localScreenshotPath);
        }
    }
    /**
     * 上传截图
     * @param localScreenshotPath
     * @return
     */
    private String uploadScreenshot(String localScreenshotPath) {
        //参数校验
        ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.NOT_FOUND_ERROR, "weburl不能为空");
        //上传到cos
        File file = new File(localScreenshotPath);
        if(!file.exists()){
            ThrowUtils.throwIf(true, ErrorCode.NOT_FOUND_ERROR, "本地截图不存在");
            return null;
        }
        //生成COS对象键
        String fileName = UUID.randomUUID().toString().substring(0,6)+"compressed.jpg";
        String cosKey = gengrateScreenshotKey(fileName);
        return cosManager.uploadFile(cosKey, file);
    }

    /**
     * 生成COS对象键
     * 格式: /screenshot/2023/12/12/xxxx.jpg
     * @param fileName
     * @return
     */
    private String gengrateScreenshotKey(String fileName) {
        String dataPath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("/screenshot/%s/%s", dataPath, fileName);
    }

    /**
     * 删除本地文件
     * @param localScreenshotPath
     */
    private void cleanupLocalScreenshot(String localScreenshotPath) {
        File file = new File(localScreenshotPath);
        if (file.exists()) {
            file.delete();
            log.info("删除本地截图文件成功:{}", localScreenshotPath);
        }
    }
}
